package com.liuzhilin.controller;

import com.liuzhilin.domain.Article;
import com.liuzhilin.domain.User;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.io.IOException;
import java.io.PrintWriter;
/*
* 用户主页文章列表
* */
@WebServlet("/userArticlePrint")
public class UserArticlePrint extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为 JSON
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        // 设置响应内容类型为 JSON
        response.setContentType("application/json");
        // 获取响应的输出流
        PrintWriter out = response.getWriter();
        // 从请求中获取选择的类
        String category = request.getParameter("category");
        //查询所有的文章信息，用集合储存起来
        List<Article> articles =UserService.getArticles(category);
        // 将用户信息转换为 JSON 格式，并返回给客户端，ObjectMapper是Jackson提供的一个类，用于将Java对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(response.getWriter(), articles);

    }
    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response){
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);

    }

}
